/**
 * 
 */
package com.zznode.client.wlanpolling.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Bean
 * 
 */
public class PingExecuteTask implements Runnable {
	private PingExecuteListener listener = null;
	private Process p = null;

	private String host;
	private String tag;
	private String pingParam;
	
	public PingExecuteTask(PingExecuteListener listener, String ip, String pingParam, String tag) {
		this.host = ip;
		this.pingParam = pingParam;
		this.tag = tag;
		this.listener = listener;		
	}
	
	public PingExecuteTask(PingExecuteListener listener, String ip, int count, String tag) {
		this.host = ip;
		this.listener = listener;
		this.tag = tag;
		this.pingParam = " -c " + count  + " ";
	}

	public void setPingParam(String pingParam) {
		this.pingParam = pingParam;
	}

	@Override
	public void run() {
		//ping -c 5 -s 64 host
		String cmd = "ping -c 50 " + host;
		
		if(pingParam != null) {
			cmd = "ping " + pingParam + " " + host;
		}
		 
		try {
			p = Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
		}

		BufferedReader bufferedreader = new BufferedReader(
				new InputStreamReader(p.getInputStream()), 8192);

		try {
			do {
				String line = bufferedreader.readLine();
				if (line == null) {
					bufferedreader.close();
					p.destroy();
					
					if(listener != null) {
						listener.onPingOver(tag, "end", null);
					}
					break;
				}
				if(listener != null) {
					listener.onProgressUpdate(tag, line);
				}
			} while (true);
		} catch (IOException e) {
			e.printStackTrace();
			if(listener != null) {
				listener.onPingOver(tag, e.getMessage(), e);
			}
		}
	}
}
